<template>
  <div>
    <MainContent title="员工管理" :back="true">
      <template #search-bar>
        <SearchBar inline>
          <template #normal>
            <el-form-item>
              <el-select v-model="params.insId" placeholder="请选择所属机构" clearable>
                <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in orgList" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input v-model="params.name" placeholder="员工名称" clearable>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="params.status" placeholder="状态" clearable>
                <el-option label="启用" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
          </template>
          <template #toolbar>

            <el-form-item>
              <el-button type="primary" @click="getStaffPageList">查询</el-button>

              <el-button type="primary" icon="Plus" @click="addStaff" v-has="['1015']">新增
              </el-button>
            </el-form-item>
          </template>
        </SearchBar>
      </template>

      <el-table :data="state.tableData" row-key="id" stripe default-expand-all v-loading="state.isLoading">
        <el-table-column prop="realName" label="员工姓名" min-width="180" />
        <el-table-column prop="insName" label="所属机构" min-width="150" />
        <el-table-column prop="roleName" label="当前职务" width="150" />
        <el-table-column prop="empNo" label="员工号" width="120" />
        <el-table-column prop="username" label="登录账号" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" class="ml-2" :active-value="1" :inactive-value="0" inline-prompt
              active-text="启用" inactive-text="禁用" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="bindWechat" label="是否绑定微信" width="180">
          <template #default="scope">
            {{ scope.row.bindWechat ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="160">
          <template #default="scope">
            {{ new Date(scope.row.updateTime).format("yyyy-MM-dd hh:mm") }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="230">
          <template #default="scope">
            <el-button link type="primary" size="small" v-if="!scope.row.bindWechat"
              @click="showWechatBindDialog(scope.row)">绑定微信</el-button>
            <el-button link type="danger" size="small" v-else @click="_unbindWechat(scope.row)">解绑微信</el-button>
            <el-button link type="primary" size="small" @click="editStaffForm(scope.row.id)"
              v-has="['1016']">编辑</el-button>
            <el-dropdown @command="handleCommand($event, scope.row)" placement="top">
              <div style="margin-left: 10px; cursor: pointer">
                <el-button type="primary" link size="small" v-has="['1017', '1018']">更多</el-button>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="scope.row.status" command="updateStaffStatus"
                    v-has="['1017']">停用</el-dropdown-item>
                  <el-dropdown-item v-else command="updateStaffStatus" v-has="['1017']">启用</el-dropdown-item>
                  <el-dropdown-item command="delStaff" v-has="['1018']">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination v-model:currentPage="params.current" v-model:page-size="params.size" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="state.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </MainContent>
    <el-dialog v-model="dialogFormVisible" :title="title" width="50%" :before-close="resetForm"
      :close-on-click-modal="false">
      <el-form :model="form" ref="staffForm" :rules="rules" label-width="80px">
        <el-form-item label="员工姓名" prop="realName">
          <el-input v-model="form.realName" autocomplete="off" placeholder="员工姓名" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="员工号">
          <el-input v-model="form.empNo" autocomplete="off" placeholder="员工号" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="员工职务" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择职务" clearable style="width: 100%">
            <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in roleList" />
          </el-select>
        </el-form-item>
        <el-form-item label="员工账号" prop="username">
          <el-input v-model="form.username" autocomplete="off" placeholder="员工账号" maxlength="20" show-word-limit
            :disabled="edit" />
        </el-form-item>
        <el-form-item label="员工密码" prop="password">
          <el-input v-model="form.password" autocomplete="off" placeholder="设置6至20位员工密码" />
        </el-form-item>
        <el-form-item label="数据权限">
          <el-radio-group v-model="form.dataAuth">
            <el-radio :label="0" name="type">个人<span class="intro">只能操作自己的数据</span></el-radio>
            <el-radio :label="1" name="type">所属机构<span class="intro">能操作自己和自己所属机构的数据</span>
            </el-radio>
            <el-radio :label="2" name="type">所属机构及下属机构
              <span class="intro">所属机构及下属机构能操作自己和自己所属机构及其子机构的数据</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm(staffForm, edit)">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <bind-wechat v-model:show="isShowBindWechat" :row-data="currentUserInfo"
      @bind-finished="handleBindWechatFinished"></bind-wechat>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, Ref } from "vue";
import {
  pageList,
  addNew,
  update,
  upStatus,
  detail,
  del,
} from "@/api/orgStaff";
import { allRole } from "@/api/orgPosition";
import { allOrg } from "@/api/orgManage";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { staffReq } from "@/api/modules/orgStaff";
import { positionReq } from "@/api/modules/orgPosition";
import { filterTemplate } from "@/api/modules/orgManage";
import { debounceUtils } from "@/utils/index.js";
import { useBindWechat } from "@/views/organization/compositions/useBindWechat";
import BindWechat from "@/views/organization/components/staff/BindWechat.vue";
import store from "@/store";

const router = useRouter();
const route = useRoute();
const state = reactive({
  id: "",
  isLoading: false,
  total: 0,
  tableData: [] as Array<staffReq>,
});

const params = ref({
  insId: 0,
  name: "",
  status: "",
  size: 10,
  current: 1,
});
let roleList = ref([] as Array<positionReq>);
let orgList = ref([] as Array<filterTemplate>);
let form = ref({
  insId: 0,
  id: "",
  realName: "",
  empNo: "",
  roleId: "",
  username: "",
  password: "",
  dataAuth: 0,
});
let validatePass = (rule: any, value: any, callback: any) => {
  const reg = /^[a-zA-Z0-9]{6,20}$/;
  if (value === "" && !edit.value) {
    callback(new Error("新增时请输入员工密码"));
  } else if (!reg.test(value) && !edit.value) {
    callback(new Error("密码为4至16位字母或数字"));
  } else {
    callback();
  }
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  params.value.size = val;
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  params.value.current = val;
};
let statusTitle = ref("停用");
const staffForm = ref<FormInstance>();
let edit = ref(false);
const rules = reactive({
  realName: [
    {
      required: true,
      message: "请输入员工名称",
      trigger: "blur",
    },
  ],
  roleId: [
    {
      required: true,
      message: "请选择职务",
      trigger: "blur",
    },
  ],
  username: [
    {
      required: true,
      message: "请输入员工账号",
      trigger: "blur",
    },
  ],
  password: [
    {
      validator: validatePass,
      required: false,
      trigger: "blur",
    },
  ],
});
const dialogFormVisible = ref(false);

let title = ref("新增员工");

const addStaff = () => {
  title.value = "新建员工";
  edit.value = false;
  dialogFormVisible.value = true;
};
const delStaff = (id: string | number) => {
  ElMessageBox.confirm("是否确定删除员工", "确认提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs = await del({
        id: id,
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getStaffPageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
const getStaffPageList = debounceUtils(async (): Promise<void> => {
  state.isLoading = true;
  const rs: any = await pageList(params.value);
  if (rs.code == 200) {
    state.tableData = rs.payload;
    state.total = rs.page.totalResult;
  }
  state.isLoading = false;
}, 500);
const editStaffForm = async (id: string | number): Promise<void> => {
  const rs = await detail({ id: id });
  if (rs.code == 200) {
    Object.assign(form.value, {
      ...rs.payload,
    });
    title.value = "编辑员工";
    edit.value = true;
    dialogFormVisible.value = true;
  }
};
const submitForm = (formEl: FormInstance | undefined, edit: any) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let rs;
      form.value.insId = params.value.insId;
      if (edit) {
        rs = await update(form.value);
      } else {
        rs = await addNew(form.value);
      }
      if (rs.code == 200) {
        resetForm();
        getStaffPageList();
      }
    } else {
      console.log("报错啦！请重新使一下", fields);
    }
  });
};
const resetForm = () => {
  form.value = {
    id: "",
    insId: 0,
    realName: "",
    empNo: "",
    roleId: "",
    username: "",
    password: "",
    dataAuth: 0,
  };
  staffForm.value?.resetFields();
  dialogFormVisible.value = false;
};
const updateStaffStatus = async (
  id: string | number,
  status: string | number
) => {
  ElMessageBox.confirm(status ? "确定启用吗" : "确定停用吗", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs = await upStatus({
        id: id,
        status: status,
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: status ? "启用成功" : "停用成功",
        });
        getStaffPageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
const getRoleList = async (): Promise<void> => {
  const rs = await allRole();
  if (rs.code == 200) {
    roleList.value = rs.payload;
  }
};
const getOrgList = async (): Promise<void> => {
  const rs = await allOrg();
  if (rs.code == 200) {
    orgList.value = rs.payload;
    console.log(route.params.id);
    if (route.params.id) {
      params.value.insId = parseInt(route.params.id as string);
    } else {
      params.value.insId = rs.payload[0].id;
    }
  }
};

const { isShowBindWechat, currentUserInfo, showWechatBindDialog, unbindWechat } = useBindWechat()

const handleBindWechatFinished = () => {
  ElMessage.success('已成功绑定微信')
  isShowBindWechat.value = false
  getStaffPageList()
}

const _unbindWechat = async (row: any) => {
  const rs: any = await unbindWechat(row)

  if (rs.code === 200) {
    getStaffPageList();
  }
}
const handleCommand = (command: string, row: any) => {
  if (command === "updateStaffStatus") {
    updateStaffStatus(row.id, row.status == 1 ? 0 : 1)
  } else if (command === "delStaff") {
    delStaff(row.id)
  }
}
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getOrgList();
    getStaffPageList();
    getRoleList();
  },
  {
    deep: true
  }
)
watch(params.value, (val) => {
  getStaffPageList();
});
onMounted(() => {
  getOrgList();
  getStaffPageList();
  getRoleList();
});
</script>
<style lang="scss" scoped>
:deep(.el-form) {
  text-align: left;
  margin-top: 18px;
}

:deep(.el-table) {
  margin: 0 auto;
}

.page {
  margin: 10px auto;
}

.dialog-form {
  :deep(.el-date-editor) {
    width: 100%;
  }
}

:deep(.el-radio-group) {
  display: block;
}

:deep(.el-radio) {
  display: block;
}

.intro {
  margin-left: 20px;
  font-size: 12px;
}
</style>
